package com.icoolkj.ms.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.icoolkj.ms.api.auth.dto.CaptchaDTO;
import com.icoolkj.ms.auth.service.IAuthStrategy;
import com.icoolkj.ms.common.cache.utils.RedisUtil;
import com.icoolkj.ms.common.core.constant.CommonConstants;
import com.icoolkj.ms.common.core.constant.GlobalConstants;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import com.icoolkj.ms.common.core.utils.PrincipalUtil;
import com.icoolkj.ms.common.mail.utils.MailUtils;
import org.springframework.stereotype.Service;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/23 22:37
 */
@Service("email" + IAuthStrategy.BASE_AUTH_STRATEGY)
public class AuthStrategyEmailImpl extends AbstractAuthStrategy {

    @Override
    public boolean validateCode(CaptchaDTO captchaDTO) {
        return doValidateCode(captchaDTO.getEmail(), "邮箱", captchaDTO);
    }

    /**
     * 生成验证码
     * @param captchaKey 生成验证码KEY
     * @return 验证结果
     */
    @Override
    public ServerResponseEntity generateCaptcha(String captchaKey) {
        if (!PrincipalUtil.isEmail(captchaKey)) {
            logger.error("邮箱格式不正确 => {}", captchaKey);
            return ServerResponseEntity.fail("邮箱格式不正确");
        }
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + captchaKey;
        String code = RandomUtil.randomNumbers(4);
        RedisUtil.set(verifyKey, code, CommonConstants.CAPTCHA_EXPIRATION);
        try {
            MailUtils.sendText(captchaKey, "登录验证码", "您本次验证码为：" + code + "，有效性为" + CommonConstants.CAPTCHA_EXPIRATION + "秒，请尽快填写。");
        } catch (Exception e) {
            logger.error("验证码短信发送异常 => {}", e.getMessage());
            return ServerResponseEntity.fail(e.getMessage());
        }
        return ServerResponseEntity.success();
    }

}
